﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NextCMS.Models;

public partial class WebAdmin_TemplateEdit : WebadminBasePage
{
    int Id = 0;
    public string MasterPageCss = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        int.TryParse(Convert.ToString(Request.QueryString["Id"]), out Id);
        if (Id > 0)
        {
            TemplatesHelper cc = new TemplatesHelper();
            TemplateModel mp = cc.GetById(Id);

            SiteResourcesHelper srh = new SiteResourcesHelper();
            SiteResourceModel srm = srh.GetById(mp.WebResourceId);


            Session["FileManager"] = "/Templates/" + srm.FolderName + "/";
            elm1.FilebrowserBrowseUrl = "FileManager/Default.aspx?SessionId=" + Session.SessionID;
            if (Request.Form["elm1"] != null)
            {
                mp.Content = Convert.ToString(Request.Form["elm1"]);
                if (Convert.ToString(Request.Form["hidRemoveSection"]) == "Yes")
                    SavePage(true, mp);
                else
                    SavePage(false, mp);
                elm1.Text = mp.Content;
            }
            else
            {

                elm1.Text = mp.Content;
            }
            MasterPageCss = GetAllCss(srm.FolderName);
            elm1.ContentsCss = MasterPageCss;
            elm1.CKEditorInstanceEventHandler = new System.Collections.Generic.List<object>();
            elm1.CKEditorInstanceEventHandler.Add(new object[] { "instanceReady", "function (evt) { ExecuteCommand('maximize');test(evt);}" });

            
        }
    }
    

    void SavePage(bool RemoveSection, TemplateModel cModel)
    {
        List<PageSections> lstSections = new List<PageSections>();
        TemplatesHelper cc = new TemplatesHelper();
        lstSections = cModel.lstPageSections;
        string RemovedSections = "";
        List<Guid> removedIds = new List<Guid>();
        foreach (PageSections ps in cModel.lstPageSections)
        {
            if (!cModel.Content.Contains("[{" + ps.Name + "}]"))
            {

                if (RemoveSection)
                {
                    PageModulesHelper pmc = new PageModulesHelper();
                    IEnumerable<PageModuleModel> lstPageModuleModel = pmc.GetById(ps.Id).ToList();
                    foreach (PageModuleModel pmm in lstPageModuleModel)
                    {
                        PageContentsHelper pcc = new PageContentsHelper();
                        pmc.Delete(pmm.Id);
                    }
                    removedIds.Add(ps.Id);
                }
                else
                {
                    RemovedSections = RemovedSections != "" ? RemovedSections + ", [{" + ps.Name + "}]" : "[{" + ps.Name + "}]";
                }
            }
        }
        foreach (Guid id in removedIds)
            lstSections.Remove(lstSections.Where(c => c.Id == id).FirstOrDefault());
        if (!String.IsNullOrEmpty(RemovedSections))
        {
            //lblError.Text = "Do you want to remove " + RemovedSections + " section(s) and all related contents?";
            //divError.Visible = true;
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "f", "ConfirmSectionRemove('" + "Do you want to remove " + RemovedSections + " section(s) and all related contents?" + "');", true);
            return;
        }

        int SectionIndex = 0;
        do
        {
            SectionIndex = cModel.Content.IndexOf("[{Section}]");
            if (SectionIndex >= 0)
            {
                PageSections ps = new PageSections();
                ps.Id = Guid.NewGuid();
                if (lstSections.Count() > 0)
                    ps.SectionId = lstSections.Max(c => c.SectionId) + 1;
                else
                    ps.SectionId = 1;

                ps.Name = "Section" + ps.SectionId;

                lstSections.Add(ps);
                cModel.Content = cModel.Content.Remove(SectionIndex, 11);
                cModel.Content = cModel.Content.Insert(SectionIndex, "[{" + ps.Name + "}]");
            }

        } while (SectionIndex > 0);

        cModel.Id = Id;
        cModel.lstPageSections = lstSections;

        cc.Edit(cModel);
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "f", "self.close();", true);
        if (Convert.ToString(Request.QueryString["Type"]) == "AddTemplate")
        {
            Response.Redirect("~/WebAdmin/ManageMasterPages.aspx");
        }
    }
}